<template>
  <div class="thumnail" v-loading="loading">

    <div class="list">
      <ul>
        <li v-for="(item,index) in thumbnailList" :key="item.id" :style="{width:thumbnailWidth,height:thumbnailHeight,'line-height':thumbnailHeight}">
          <span class="btn-group">
            <span class="btn-item">
              <i class="el-icon-caret-left" @click="changeThumbnailIndex(index,'left')" v-if="index !==0"></i>
              <i class="el-icon-zoom-in" @click="zoomThumb(item)"></i>
              <i class="el-icon-delete" @click="deleteThumb(item)"></i>
              <i class="el-icon-caret-right" @click="changeThumbnailIndex(index,'right')" v-if="index+1 !==thumbnailList.length"></i>
            </span>
          </span>
          <img :src="baseURL+item.url" :style="{width:thumbnailWidth,height:thumbnailHeight}">
        </li>
        <div class="upload-file" v-if="thumbnailList.length < limit">
          <el-upload action="" class="avatar-uploader" :show-file-list="false" :before-upload="beforeUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" :style="{width:thumbnailWidth,height:thumbnailHeight,'line-height':thumbnailHeight}"></i>
          </el-upload>
        </div>
      </ul>
    </div>
    <el-dialog :visible.sync="zoomThumbnail.show" :width="option.autoCropWidth+50+'px'">
      <img :src="baseURL+zoomThumbnail.url">
    </el-dialog>

    <el-dialog title="이미지 업로드" :width="option.autoCropWidth+150+'px'" :visible.sync="showCropWindows" :close-on-click-modal="false" v-loading="loading">
      <div class="cropper-content">
        <div class="cropper" :style="{width:option.autoCropWidth+100+'px',height:option.autoCropHeight+100+'px'}" >
          <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true"
            :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original"
            :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight"
            :fixedBox="option.fixedBox"></vueCropper>
        </div>
        <div class="footer-btn">
          <div class="scope-btn">
            <el-button type="primary" icon="el-icon-zoom-in" @click="changeScale(1)" circle></el-button>
            <el-button type="primary" icon="el-icon-zoom-out" @click="changeScale(-1)" circle></el-button>
            <el-button type="primary" icon="el-icon-refresh-left" @click="rotateLeft" circle></el-button>
            <el-button type="primary" icon="el-icon-refresh-right" @click="rotateRight" circle></el-button>
            <el-button type="primary" @click="upload" round>上传</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    VueCropper
  } from 'vue-cropper' //截图插件
  import {
    uploadFile,
    deleteFile
  } from '@/api/files'
  export default {
    name: 'UploadThumbnail',
    components: {
      VueCropper,
    },
    props: ["thumbnailLists","limit","width","height","point"],
    data() {
      return {
        thumbnailWidth:this.point/this.limit+'px',
        thumbnailHeight:this.height/(this.width/(this.point/this.limit))+'px',
        thumbnailList:this.thumbnailLists,
        baseURL: process.env.BASE_API,
        imageUrl: '',
        showCropWindows: false,
        zoomThumbnail: {
          show: false,
          url: '',
        },
        loading: false,
        file: {
          name: '',
          data: '',
        },
        option: {
          img: '',
          outputSize: 0.5, //裁剪生成图片的质量
          full: false, //输出原图比例截图
          outputType: 'png',
          canMove: true, //上传图片是否可以移动
          original: true, //上传图片按照原始比例渲染
          canMoveBox: true,  //截图框能否拖动
          autoCrop: true, //是否默认生成截图框
          //fixed:false, //是否开启截图框宽高固定比例
          autoCropWidth: this.width,
          autoCropHeight: this.height,
          fixedBox: true, //固定截图框大小 不允许改变
        }
      }
    },
    watch: {
      thumbnailLists(val) {
        this.thumbnailList = val; //监听修改 同步
      }
    },
    methods: {
      deleteThumb(file) {
        this.$confirm('회복할 수 없는 조작입니다!', '팁스', {
          confirmButtonText: '삭제',
          cancelButtonText: '취소',
          type: 'warning'
        }).then(() => {
          deleteFile(file).then(response => {
            if (response) {
              this.$emit('deleteThumbnail', file);
              this.$message({
              	type: 'success',
              	message: '삭제되엿습니다'
              });
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '취소되엿습니다'
          });
          reject()
        });
      },
      zoomThumb(file) {
        this.zoomThumbnail.url = file.url;
        this.zoomThumbnail.show = true;
      },
      changeThumbnailIndex(index,type) {
        var num = type==='left'?index-1:index+1;
        this.$emit('changeThumbnailIndex', index,num);
      },
      changeScale(num) { //放大缩小
        num = num || 1
        this.$refs.cropper.changeScale(num)
      },
      rotateLeft() { //向左旋转
        this.$refs.cropper.rotateLeft()
      },
      rotateRight() { //向右旋转
        this.$refs.cropper.rotateRight()
      },
      upload() { //上传图片
        this.loading = true;
        this.$refs.cropper.getCropData((data) => {
          this.file.data = data;
          uploadFile(this.file).then(response => {
            this.$emit('addThumbnail', response.data);
            this.showCropWindows = false;
            this.loading = false;
            this.$message({
              type: 'success',
              message: '업로드 되엿습니다'
            });
          })
        })
      },
      beforeUpload(file) {
        this.loading = true;
        this.file.name = file.name;
        if (file.type.substring(0, 5) !== 'image') {
          this.$message({
            type: 'error',
            message: '이미지만 가능'
          });
          this.loading = false;
          return false
        }
        var reader = new FileReader();
        reader.readAsDataURL(file); // 读出 base64
        reader.onloadend = () => {
          // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
          var dataURL = reader.result;
          // 下面逻辑处理
          this.option.img = dataURL
          this.showCropWindows = true;
          this.loading = false;
        }
        return false
      }
    }
  }
</script>
<style>
  .thumnail .el-dialog__title {
    font-size: 12px;
  }
  .upload-file .avatar-uploader-icon {
    font-size: 28px;
    color: #999;
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .cropper-content {

    .footer-btn {
      margin-top: 20px;
      display: flex;
      display: -webkit-flex;
    }
  }

  .upload-file {
    float: left;
  }

  .thumnail {
    ul:after {
      content: '';
      display: table;
      clear: both;
    }

    ul {
      padding: 0px;
      margin: 0px;

      li {
        border: 1px solid #ccc;
        .btn-item {
          i {
            background: rgba(0, 0, 0, 0.8);
            width: 30px;
            height: 30px;
            border-radius: 15px;
            font-size: 16px;
            line-height: 30px;
            text-align: center;
            color: #ccc;
          }

          i:hover {
            color: #fff;
            cursor: pointer;
          }
        }

        list-style:none;
        float: left;
        margin-right: 15px;
        overflow: hidden;
        position: relative;

        span:hover {
          opacity: 1;
        }

        span {
          position: absolute;
          width: 100%;
          height: 100%;
          left: 0;
          top: 0;
          cursor: default;
          text-align: center;
          color: #fff;
          opacity: 0;
          font-size: 20px;
          background-color: rgba(0, 0, 0, .5);
          -webkit-transition: opacity .3s;
          transition: opacity .3s;

          i {
            color: #fff;
            position: static;
            font-size: inherit;
          }
        }
      }
    }

    .avatar-uploader-icon {
      cursor: pointer;
      background-color: #fbfdff;
      border: 1px dashed #c0ccda;
      border-radius: 6px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      vertical-align: top;
    }

    .avatar-uploader-icon:hover {
      border-color: #409EFF;
    }
  }
</style>
